const axios = require('axios')
const md5 = require('md5')
const encryptTools = require('./encrypt')
const GLOBAL = require('./global')

const instance = axios.create({
  headers: GLOBAL.headers,
})

let DISTANCE = '3000'
let LONGITUDE = '31.28404' // 自行更改
let LATITUDE = '118.3804121' // 自行更改
let returnIfo = {}

function justRun(imeiCode, distance, longitude, latitude) {
  DISTANCE = distance
  LONGITUDE = longitude
  LATITUDE = latitude
  returnIfo = {}
  encryptTools.randomGenerateTable()
  console.log('run ' + imeiCode + ' ' + DISTANCE + ' ')

  returnIfo.input = 'run ' + imeiCode + ' ' + DISTANCE + ' '
  returnIfo.input = {
    imeiCode: imeiCode,
    distance: DISTANCE
  }

  return new Promise((resolve, reject) => {
    instance
      .get(GLOBAL.apiRoot + '/%7Btoken%7D/QM_Users' + '/Login_AndroidSchool?IMEICode=' + imeiCode)
      .then(res => {
        if (res.data.Success) {
          let data = res.data.Data
          createLoginData(data)
          resolve(returnIfo)
        } else {
          returnIfo.err = res.data.ErrMsg
          reject(returnIfo)
        }
      })
      .catch(err => {
        returnIfo.err = err
        reject(returnIfo)
      })
  })
}

function createLoginData(data) {
  let UserId = data.UserId
  let timespan = Date.now()
  let nonce = 100000 + randInt(9900000)
  let sign = md5(data.Token + nonce + timespan + UserId).toUpperCase()
  let headers = {
    UserId,
    timespan,
    nonce,
    sign,
  }
  // setTimeout(() => {
  let postIfo = randomGenerateInfo()
  postIfo.Token = data.Token
  postData(headers, postIfo)
  // }, 1000)
}

function postData(headers, postIfo) {
  // returnIfo.postIfo = postIfo

  let allHeaders = Object.assign(GLOBAL.headers, headers)
  allHeaders.Accept = 'text/html'
  allHeaders['Accept-Encoding'] = 'gzip'
  allHeaders.Connection = 'Keep-Alive'

  let requestInstance = axios.create({
    headers: allHeaders,
  })

  let Token = postIfo.Token
  let runStep = postIfo.runStep
  let runTime = postIfo.runTime
  let runDistance = postIfo.runDistance

  let str = GLOBAL.apiRoot + `/${Token}/QM_Runs/SRS?S1=${LONGITUDE}&S2=${LATITUDE}&S3=${DISTANCE}`
  console.log(str)
  requestInstance
    .get(GLOBAL.apiRoot + `/${Token}/QM_Runs/SRS?S1=${LONGITUDE}&S2=${LATITUDE}&S3=${DISTANCE}`)
    .then(res => {
      console.log(res.data)
      let data = res.data.Data
      // returnIfo.runIfo = data
      let RunId = data.RunId
      console.log(
        `${GLOBAL.apiRoot}/${Token}/QM_Runs/ES?S1=${RunId}&S4=${encryptTools.encrypt(
          runTime
        )}&S5=${encryptTools.encrypt(runDistance)}&S6=${data.Routes
        }&S7=1&S8=${encryptTools.getTable()}&S9=${encryptTools.encrypt(runStep)}`
      )

      requestInstance
        .get(
          `${GLOBAL.apiRoot}/${Token}/QM_Runs/ES?S1=${RunId}&S4=${encryptTools.encrypt(
            runTime
          )}&S5=${encryptTools.encrypt(runDistance)}&S6=${data.Routes
          }&S7=1&S8=${encryptTools.getTable()}&S9=${encryptTools.encrypt(runStep)}`
        )
        .then(res => {
          console.log(res.data)
          // returnIfo.success = res.data
        })
        .catch(err => {
          console.log(err)
          // returnIfo.err = err
        })
    })
    .catch(err => {
      console.log(err)
      // returnIfo.err = err
    })
}

function randomGenerateInfo() {
  let runTime = (1000 + randInt(400)).toString()
  if (Number(DISTANCE) === 2400) {
    runTime = (960 + randInt(240)).toString()
  }
  let runDistance = (Number(DISTANCE) + randInt(4)).toString()
  let runStep = (2014 + randInt(512)).toString()
  // console.log(`random ifo: runtime: ${runTime}, runDistance: ${runDistance}, step: ${runStep}`)
  // returnIfo.randomIfo = `random ifo: runtime: ${runTime}, runDistance: ${runDistance}, step: ${runStep}`
  returnIfo.randomIfo = {
    '时间': runTime,
    '距离': runDistance,
    '步数': runStep
  }
  return {
    runTime,
    runDistance,
    runStep,
  }
}

function randInt(max) {
  return Math.floor(Math.random() * max) + 1
}

exports.justRun = justRun
